package com.lizemin;

import com.lizemin.entity.*;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.sql.Date;

/**
 * @author: lizemin
 * @version: 1.0
 */
public class AnnotationTest2 {

    Session session = null;
    Transaction tx = null;

    @Before
    public void init(){
        // A SessionFactory is set up once for an application!
        final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
                .configure("hibernate.cfg.xml") // configures settings from hibernate.cfg.xml
                .build();
        SessionFactory sessionFactory = new MetadataSources(registry)
                .buildMetadata()
                .buildSessionFactory();
        //创建SQL session连接
        session = sessionFactory.openSession();
        //开启事务
        tx = session.beginTransaction();
    }

    @After
    public void closeConnection() {
        if (null != session && session.isOpen()){
            //关闭session
            session.close();
        }
    }
    
    @Test
    public void test1(){
        Account account = new Account();
        account.setName("李泽民");

        Account account2 = new Account();
        account2.setName("李泽");

        Course course = new Course();
        course.setName("java");

        Course course2 = new Course();
        course2.setName("C#");

        /**
         * 前面的实体类上可以看出，是account表在负责数据的增删改查
         */
        account.getCourses().add(course);
        course.getAccounts().add(account);

        account2.getCourses().add(course2);
        course2.getAccounts().add(account2);

        session.save(account);
        session.save(account2);
        session.save(course);
        session.save(course2);

        tx.commit();
    }

    
}
